//
//  RegisterViewController.m
//  TeslaCharging
//
//  Created by glave on 14-6-18.
//  Copyright (c) 2014年 Glavesoft. All rights reserved.
//

#import "RegisterViewController.h"
//#import "AddChangingPileVC.h"
#import "SVProgressHUD.h"
#import "Glob.h"
@interface RegisterViewController ()

@end

@implementation RegisterViewController
@synthesize imageView=_imageView,nameField = _nameField, pwdField = _pwdField,registerButton = _registerButton, registerView = _registerView,czOrsjBtn=czOrsjBtn,czOrsjImg = _czOrsjImg,czOrsjLab=_czOrsjLab,autoLoginBtn=_autoLoginBtn,autoLoginImg=_autoLoginImg,autoLoginLab=_autoLoginLab;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"注册";
        self.view.backgroundColor = mRGBColor(240, 240, 240);
        [self.navigationItem setLeftBarButtonItem:[Glob getNavigationBarBackButton:self imgName:@"fanhuianniu.png"]];
    }
    return self;
}

-(void)back:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)loadView
{
    [super loadView];
    
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    CGSize size = [[UIScreen mainScreen] bounds].size;
    if (IOS7) {
        _registerView = [[TPKeyboardAvoidingScrollView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    }
    else
        _registerView = [[TPKeyboardAvoidingScrollView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    [self.view addSubview:_registerView];
//    _headBtn = [[UIButton alloc] initWithFrame:CGRectMake(size.width/2 - 50, 10, 100, 100)];
//    [_headBtn setImage:[UIImage imageNamed:@"icon_head.png"] forState:UIControlStateNormal];
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake((size.width-80)/2, 20, 80, 79)];
    _imageView.image = [UIImage imageNamed:@"zhucetupian.png"];
//    [self.view addSubview:_imageView];
    _nameField = [[UITextField alloc] initWithFrame:CGRectMake(20, _imageView.bottom + 20, size.width - 40,40)];
    _nameField.backgroundColor = [UIColor whiteColor];
    _nameField.layer.borderColor = mRGBColor(208, 205, 206).CGColor;
    _nameField.layer.borderWidth =1.0;
    _nameField.layer.cornerRadius =0.0;
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 40)];    //左端缩进15像素
    _nameField.leftView = view1;
    _nameField.leftViewMode = UITextFieldViewModeAlways;
    _nameField.placeholder = @"账号名 (六个字符以上,不可中文)";
    _nameField.text = @"";
    _nameField.tag = 1001;
    _nameField.delegate = self;
    _nameField.keyboardType = UIKeyboardTypeNamePhonePad;
    _nameField.returnKeyType = UIReturnKeyNext;
    [_nameField addTarget:self action:@selector(accessCodeTextFiledNext:) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    _nickNameField = [[UITextField alloc] initWithFrame:CGRectMake(20,_nameField.bottom + 20, size.width - 40,40)];
    _nickNameField.backgroundColor = [UIColor whiteColor];
    _nickNameField.layer.borderColor = mRGBColor(208, 205, 206).CGColor;
    _nickNameField.layer.borderWidth =1.0;
    _nickNameField.layer.cornerRadius =0.0;
    UIView *view11 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 40)];    //左端缩进15像素
    _nickNameField.leftView = view11;
    _nickNameField.leftViewMode = UITextFieldViewModeAlways;
    _nickNameField.placeholder = @"昵称";
    _nickNameField.text = @"";
    _nickNameField.tag = 10011;
    _nickNameField.delegate = self;
    _nickNameField.returnKeyType = UIReturnKeyNext;
    [_nickNameField addTarget:self action:@selector(accessCodeTextFiledNext:) forControlEvents:UIControlEventEditingDidEndOnExit];
    
//    _typeField = [[UITextField alloc] initWithFrame:CGRectMake(20, _nickNameField.bottom + 20, size.width - 40,40)];
//    _typeField.backgroundColor = [UIColor whiteColor];
//    _typeField.layer.borderColor = RGBCOLOR(208, 205, 206).CGColor;
//    _typeField.layer.borderWidth =1.0;
//    _typeField.layer.cornerRadius =0.0;
//    UIView *view5 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 40)];    //左端缩进15像素
//    _typeField.leftView = view5;
//    _typeField.leftViewMode = UITextFieldViewModeAlways;
//    _typeField.placeholder = @"车主/商家";
//    _typeField.text = @"";
//    _typeField.tag = 1002;
//    _typeField.delegate = self;
//    [_typeField addTarget:self action:@selector(accessCodeTextFiledNext:) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    _phoneField = [[UITextField alloc] initWithFrame:CGRectMake(20, _nickNameField.bottom + 20, size.width - 40,40)];
    _phoneField.backgroundColor = [UIColor whiteColor];
    _phoneField.layer.borderColor = mRGBColor(208, 205, 206).CGColor;
    _phoneField.layer.borderWidth =1.0;
    _phoneField.layer.cornerRadius =0.0;
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 40)];    //左端缩进15像素
    _phoneField.leftView = view2;
    _phoneField.leftViewMode = UITextFieldViewModeAlways;
    _phoneField.placeholder = @"手机号";
    _phoneField.text = @"";
    _phoneField.keyboardType = UIKeyboardTypeNumberPad;
    _phoneField.tag = 1003;
    _phoneField.delegate = self;
    _phoneField.returnKeyType = UIReturnKeyNext;
    [_phoneField addTarget:self action:@selector(accessCodeTextFiledNext:) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    _pwdField = [[UITextField alloc] initWithFrame:CGRectMake(20, _phoneField.bottom + 20, size.width - 40,40)];
    _pwdField.backgroundColor = [UIColor whiteColor];
    _pwdField.layer.borderColor = mRGBColor(208, 205, 206).CGColor;
    _pwdField.layer.borderWidth =1.0;
    _pwdField.layer.cornerRadius =0.0;
    UIView *view3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 40)];    //左端缩进15像素
    _pwdField.leftView = view3;
    _pwdField.leftViewMode = UITextFieldViewModeAlways;
    _pwdField.secureTextEntry = YES;
    _pwdField.placeholder = @"密码，8到16位字母和数字的组合";
    _pwdField.text = @"";
    _pwdField.tag = 1004;
    _pwdField.delegate = self;
    _pwdField.keyboardType = UIKeyboardTypeNamePhonePad;
    _pwdField.returnKeyType = UIReturnKeyNext;
    [_pwdField addTarget:self action:@selector(accessCodeTextFiledNext:) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    _pwd2Field = [[UITextField alloc] initWithFrame:CGRectMake(20, _pwdField.bottom + 20, size.width - 40,40)];
    _pwd2Field.backgroundColor = [UIColor whiteColor];
    _pwd2Field.layer.borderColor = mRGBColor(208, 205, 206).CGColor;
    _pwd2Field.layer.borderWidth =1.0;
    _pwd2Field.layer.cornerRadius =0.0;
    UIView *view4 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 35)];    //左端缩进15像素
    _pwd2Field.leftView = view4;
    _pwd2Field.leftViewMode = UITextFieldViewModeAlways;
    _pwd2Field.placeholder = @"重复密码";
    _pwd2Field.text = @"";
    _pwd2Field.secureTextEntry = YES;
    _pwd2Field.tag = 1005;
    _pwd2Field.delegate = self;
    _pwd2Field.returnKeyType = UIReturnKeyDone;
    [_pwd2Field addTarget:self action:@selector(accessCodeTextFiledDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    _privacyTintLab = [[UILabel alloc] initWithFrame:CGRectMake(20, _pwd2Field.bottom + 10, 300, 20)];
    _privacyTintLab.font = [UIFont systemFontOfSize:13];
    _privacyTintLab.backgroundColor = mRGBColor(240, 240, 240);
//    _privacyTintLab.backgroundColor = [UIColor blackColor];
    NSString *original = @"注册则默认阅读并同意使用条款和隐私策略";
    NSMutableAttributedString *attrTitle = [[NSMutableAttributedString alloc] initWithString:original];
    [attrTitle addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, 12)];
    [attrTitle addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(12, 7)];
    [_privacyTintLab setAttributedText:attrTitle];
    
    UITapGestureRecognizer* singleRecognizer;
    singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(SingleTap:)];
    //点击的次数
    singleRecognizer.numberOfTapsRequired = 1; // 单击
    singleRecognizer.delegate = self;
    //给self.view添加一个手势监测；
    _privacyTintLab.userInteractionEnabled=YES;
    [_privacyTintLab addGestureRecognizer:singleRecognizer];
    
    _registerButton = [[UIButton alloc] initWithFrame:CGRectMake((size.width-131)/2, _pwd2Field.bottom + 40,131, 39)];
    [_registerButton setImage:[UIImage imageNamed:@"zhuceanniu.png"] forState:UIControlStateNormal];
    [_registerButton addTarget:self action:@selector(doRegister) forControlEvents:UIControlEventTouchUpInside];
    
//    [_registerView addSubview:_headBtn];
    [_registerView addSubview:_imageView];
    [_registerView addSubview:_nameField];
    [_registerView addSubview:_nickNameField];
    [_registerView addSubview:_typeField];
    [_registerView addSubview:_phoneField];
    [_registerView addSubview:_pwdField];
    [_registerView addSubview:_pwd2Field];
    [_registerView addSubview:_registerButton];
    [_registerView addSubview:_privacyTintLab];
    
    [_registerView setContentSize:CGSizeMake(self.view.width, _registerButton.bottom + 70)];
    [self.view addSubview:_registerView];
}

-(void)SingleTap:(UITapGestureRecognizer*)recognizer
{
    NSLog(@"隐私策略");
    NSURL *url = nil;
    url = [NSURL URLWithString:@"http://oa.glavesoft.com/Agreement.aspx"];
    
    TOWebViewController *webViewController = [[TOWebViewController alloc] initWithURL:url];
    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:webViewController] animated:YES completion:nil];
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (textField.tag == 1002)
    {
        [self.view endEditing:YES];
//        [self showMore:textField];
        return NO;
    }
    return YES;
}

-(void)accessCodeTextFiledDone:(id)sender
{
    //开始注册
    [self doRegister];
}

-(void)accessCodeTextFiledNext:(id)sender
{
    UITextField *field = sender;
    if (field.tag == 1001) {
        [_nickNameField becomeFirstResponder];
    }
    else if (field.tag == 10011) {
        [_phoneField becomeFirstResponder];
    }
    else if (field.tag == 1002)
    {
        [_phoneField becomeFirstResponder];
    }
    else if (field.tag == 1003)
    {
        [_pwdField becomeFirstResponder];
    }
    else if (field.tag == 1004)
    {
        [_pwd2Field becomeFirstResponder];
    }
}

//普通用户登录
- (void)doRegister
{
    _registerButton.userInteractionEnabled = NO;
    NSString *user = self.nameField.text;
    NSString *nickName = self.nickNameField.text;
    NSString *phone = self.phoneField.text;
    NSString *type = @"车主";
    if ([type isEqualToString:@"车主"]) {
        type = @"0";
    }
    else
    {
        type = @"1";
    }
    NSString *pwd = self.pwdField.text;
    NSString *pwd2 = self.pwd2Field.text;
    NSRegularExpression *regularexpressionPhone = [[NSRegularExpression alloc]
                                                   initWithPattern:REGPHONE
                                                   options:NSRegularExpressionCaseInsensitive
                                                   error:nil];
    NSUInteger isMatchPhone = [regularexpressionPhone numberOfMatchesInString:phone
                                                                      options:NSMatchingReportProgress
                                                                        range:NSMakeRange(0, phone.length)];
    NSRegularExpression *regularexpressionPass = [[NSRegularExpression alloc]
                                                   initWithPattern:REGPASS
                                                   options:NSRegularExpressionCaseInsensitive
                                                   error:nil];
    NSUInteger isMatchPass = [regularexpressionPass numberOfMatchesInString:pwd
                                                                      options:NSMatchingReportProgress
                                                                        range:NSMakeRange(0, pwd.length)];
    if (user == nil || [user isEqualToString:@""] || user.length < 6)
    {
        [SVProgressHUD showErrorWithStatus:@"用户名不能为空或少于六位"];
        [SVProgressHUD performSelector:@selector(dismiss) withObject:nil afterDelay:1.2f];
        _registerButton.userInteractionEnabled = YES;
    }
    else if (nickName == nil || [nickName isEqualToString:@""])
    {
        [SVProgressHUD showErrorWithStatus:@"昵称不能为空"];
        [SVProgressHUD performSelector:@selector(dismiss) withObject:nil afterDelay:1.2f];
        _registerButton.userInteractionEnabled = YES;
    }
    else if ((phone == nil || [phone isEqualToString:@""]) || !isMatchPhone)
    {
        [SVProgressHUD showErrorWithStatus:@"手机号不能为空或格式不对"];
        [SVProgressHUD performSelector:@selector(dismiss) withObject:nil afterDelay:1.2f];
        _registerButton.userInteractionEnabled = YES;
    }
    else if (type == nil || [type isEqualToString:@""])
    {
        [SVProgressHUD showErrorWithStatus:@"车主/商家不能为空"];
        [SVProgressHUD performSelector:@selector(dismiss) withObject:nil afterDelay:1.2f];
        _registerButton.userInteractionEnabled = YES;
    }
    else if([pwd rangeOfString:@" "].location !=NSNotFound)
    {

        [SVProgressHUD showErrorWithStatus:@"密码不能为空或格式不对"];
        [SVProgressHUD performSelector:@selector(dismiss) withObject:nil afterDelay:1.2f];
        _registerButton.userInteractionEnabled = YES;

    }
    else if ((pwd == nil || [pwd isEqualToString:@""]) || !isMatchPass)
    {
        [SVProgressHUD showErrorWithStatus:@"密码不能为空或格式不对"];
        [SVProgressHUD performSelector:@selector(dismiss) withObject:nil afterDelay:1.2f];
        _registerButton.userInteractionEnabled = YES;
        
    }
    else if (![pwd isEqualToString:pwd2])
    {
        [SVProgressHUD showErrorWithStatus:@"两次密码输入不一致"];
        [SVProgressHUD performSelector:@selector(dismiss) withObject:nil afterDelay:1.2f];
        _registerButton.userInteractionEnabled = YES;
        
    }
    else
    {
        //活动详细 传参
        NSMutableArray *params1=[NSMutableArray array];
        [params1 addObject:[NSDictionary dictionaryWithObjectsAndKeys:user,@"username", nil]];
        [params1 addObject:[NSDictionary dictionaryWithObjectsAndKeys:type,@"usertype", nil]];
        [params1 addObject:[NSDictionary dictionaryWithObjectsAndKeys:nickName,@"nickname", nil]];
        [params1 addObject:[NSDictionary dictionaryWithObjectsAndKeys:phone,@"phone", nil]];
        [params1 addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"cityarea", nil]];
        [params1 addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"",@"pic", nil]];
        [params1 addObject:[NSDictionary dictionaryWithObjectsAndKeys:pwd,@"password", nil]];
        [params1 addObject:[NSDictionary dictionaryWithObjectsAndKeys:DEFAULT_CODE,@"code", nil]];
//        ASIServiceArgs *args2=[[ASIServiceArgs alloc] init];
//        args2.methodName=@"AddCarUser";
//        args2.soapParams = params1;
//        
//        NSLog(@"soap=%@\n",args2.bodyMessage);
//        
//        ASIServiceHTTPRequest *request=[ASIServiceHTTPRequest requestWithArgs:args2];
//        [request success:^{
//            _registerButton.userInteractionEnabled = YES;
//            NSLog(@"请求头=%@",request.ServiceArgs.headers);
//            NSLog(@"请求body=%@",request.ServiceArgs.bodyMessage);
//            if (request.ServiceResult.success) {
//                id json=[request.ServiceResult json];
//                if ([json isKindOfClass:[NSDictionary class]]) {
//                    NSDictionary *dic=json;
//                    if ([[dic objectForKey:@"Result"] isEqualToString:@"1"]) {
//                        /*暂时屏蔽客户端添加充电桩
//                        UIAlertView *altView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"恭喜，注册成功，是否添加充电桩信息？" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
//                        [altView show];
//                         */
//                        UIAlertView *altView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"恭喜，注册成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                        altView.tag = 1001;
//                        [altView show];
//                    }
//                    else if ([[dic objectForKey:@"Result"] isEqualToString:@"0"]) {
//                        UIAlertView *altView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该用户名已被注册" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                        [altView show];
//                    }
//                    else {
//                        UIAlertView *altView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"注册失败，请重试" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//                        [altView show];
//                    }
//                    
//                }
//
//            }
//            else{
//            }
//        } failure:^{
//            NSLog(@"error=%@\n",request.error.description);
//            _registerButton.userInteractionEnabled = YES;
//        }];
    }
}

//-(void)importFromLocal:(id)sender{
//    
//    KxMenuItem *item=(KxMenuItem *)sender;
//    
//    _typeField.text=item.title;
//    
//    [_phoneField becomeFirstResponder];
//}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1001) {
        if (buttonIndex == 0) {
            //放弃
            NSLog(@"放弃");
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        else
        {
            //添加充电桩信息
            NSLog(@"添加");
//            AddChangingPileVC *addVC = [[AddChangingPileVC alloc] initWithNibName:nil bundle:nil];
//            [addVC setHidesBottomBarWhenPushed:YES];
//            [self.navigationController pushViewController:addVC animated:YES];
        }
    }
    else
    {
        if (buttonIndex == 0) {
            //放弃
            NSLog(@"放弃");
            //        [self.navigationController popToRootViewControllerAnimated:YES];
        }
        else
        {
            //添加充电桩信息
            NSLog(@"添加");
//            AddChangingPileVC *addVC = [[AddChangingPileVC alloc] initWithNibName:nil bundle:nil];
//            [addVC setHidesBottomBarWhenPushed:YES];
//            [self.navigationController pushViewController:addVC animated:YES];
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
/*-(CGRect)placeholderRectForBounds:(CGRect)bounds
{
    
    //return CGRectInset(bounds, 20, 0);
    CGRect inset = CGRectMake(bounds.origin.x, bounds.origin.y+5, bounds.size.width, bounds.size.height);//更好理解些
    return inset;
}*/

@end
